package br.elsa.survey.view.beans.managed;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;

import br.elsa.survey.dao.exceptions.DataNotFoundException;
import br.elsa.survey.domain.questions.Question;
import br.elsa.survey.services.QuestionService;
import br.elsa.survey.view.messages.ViewMessages;

/**
 * Component that controls the questions management view of the system.
 * 
 * <p>
 * This component provides data to populate the questions management view,
 * handles events from this view, like remove question button clicked.
 * </p>
 * 
 * @author diego
 * @since 2010-10-20
 * 
 */
@ViewScoped
@ManagedBean
public class QuestionsManagementView {

	/**
	 * Service that implements all business logic over {@link Question} domain
	 * components
	 */
	@EJB
	private QuestionService questionService;

	/**
	 * Component used to add messages of different levels in the view.
	 */
	@Inject
	private ViewMessages viewMessages;

	/**
	 * List of all created {@link Question} in the system
	 */
	private List<Question> questions;

	public QuestionsManagementView() {

	}

	public QuestionsManagementView(QuestionService questionService, ViewMessages viewMessages) {

		this.questionService = questionService;
		this.viewMessages = viewMessages;
	}

	/**
	 * Initializes the list of created {@link Question} before the view is
	 * shown, in the {@link PostConstruct} event of this bean.
	 * 
	 * This method will be invoked just once by the {@link PostConstruct} event,
	 * since this component is {@link ViewScoped}.
	 */
	@PostConstruct
	public void loadQuestions() {

		try {
			questions = questionService.getAllQuestions();

		} catch (DataNotFoundException e) {
			viewMessages.addWarnMessage("There is no question registered in the system");
			questions = null;
		}
	}

	/**
	 * Removes a {@link Question} from the system and shows an information
	 * message in the view.
	 * 
	 * @param question
	 *            the question to be removed
	 */
	public void removeQuestion(Question question) {

		questionService.remove(question);
		viewMessages.addInfoMessage("Question removed from system");
		loadQuestions();
	}

	/**
	 * Gets the list of created {@link Question} in the system
	 * 
	 * @return {@link List} of {@link Question}
	 */
	public List<Question> getQuestions() {

		return questions;
	}
}
